package com.purong.purong.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.ViewCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ScaleXSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ListAdapter;
import android.widget.ListView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/7/18.
 */
public class CommonUtil {
    /**
     * 获取状态栏高度
     * */
    public static int getStatusBarHeight(Context context){
        int statusBarHeight1 = -1;
        //获取status_bar_height资源的ID
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = context.getResources().getDimensionPixelSize(resourceId);
        }
        return statusBarHeight1;
    }
    public static int getScreenHeight(Context mContext) {
        WindowManager wm = (WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getHeight();
    }

    public static int getScreenWidth(Context mContext) {
        WindowManager wm = (WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getWidth();
    }

    public static int[] getImageWidthHeight(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();

        /**
         * 最关键在此，把options.inJustDecodeBounds = true;
         * 这里再decodeFile()，返回的bitmap为空，但此时调用options.outHeight时，已经包含了图片的高了
         */
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此时返回的bitmap为null
        /**
         *options.outHeight为原始图片的高
         */
        return new int[]{options.outWidth, options.outHeight};
    }

    public static String getIMEI(Context mContext) {
//        TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        String mDevIDShort = "35" + Build.BOARD.length() % 10 +
                Build.BRAND.length() % 10 +
                Build.CPU_ABI.length() % 10 +
                Build.DEVICE.length() % 10 +
                Build.DISPLAY.length() % 10 +
                Build.HOST.length() % 10 +
                Build.ID.length() % 10 +
                Build.MANUFACTURER.length() % 10 +
                Build.MODEL.length() % 10 +
                Build.PRODUCT.length() % 10 +
                Build.TAGS.length() % 10 +
                Build.TYPE.length() % 10 +
                Build.USER.length() % 10;

        String mWlanMac;
        if (Build.VERSION.SDK_INT >= 23) {
            mWlanMac = getMacAddress();
        } else {
            WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
            mWlanMac = wm.getConnectionInfo().getMacAddress();
        }

        return "android_" + mDevIDShort + mWlanMac;
    }

    public static String getMacAddress() {
        try {

            String address = null;
            // 把当前机器上的访问网络接口的存入 Enumeration集合中
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface netWork = interfaces.nextElement();
                // 如果存在硬件地址并可以使用给定的当前权限访问，则返回该硬件地址（通常是 MAC）。
                byte[] by = netWork.getHardwareAddress();
                if (by == null || by.length == 0) {
                    continue;
                }
                StringBuilder builder = new StringBuilder();
                for (byte b : by) {
                    builder.append(String.format("%02X:", b));
                }
                if (builder.length() > 0) {
                    builder.deleteCharAt(builder.length() - 1);
                }
                String mac = builder.toString();
                Log.d("mac", "interfaceName=" + netWork.getName() + ", mac=" + mac);
                // 从路由器上在线设备的MAC地址列表，可以印证设备Wifi的 name 是 wlan0
                if (netWork.getName().equals("wlan0")) {
                    Log.d("mac", " interfaceName =" + netWork.getName() + ", mac=" + mac);
                    address = mac;
                }
            }
            return address;

        } catch (Exception e) {
            return "";
        }
    }

    /**
     * unicode 转字符串
     */
    public static String unicode2String(String unicode) {

        StringBuffer string = new StringBuffer();

        String[] hex = unicode.split("\\\\u");

        for (int i = 1; i < hex.length; i++) {

            // 转换出每一个代码点
            int data = Integer.parseInt(hex[i], 16);

            // 追加成string
            string.append((char) data);
        }

        return string.toString();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static boolean isNetConnected(Context context) {
        if (context == null)
            return false;
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetInfo = manager.getActiveNetworkInfo();
        if (mNetInfo == null)
            return false;
        if (!mNetInfo.isConnected()) {
            return false;
        } else {
            return true;
        }
    }

    public static boolean isNetworkWifi(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo == null)
            return false;
        if (netInfo.getType() == ConnectivityManager.TYPE_WIFI)
            return true;
        return false;
    }

    public static boolean isLiveStreamingAvailable() {
        // Todo: Please ask your app server, is the live streaming still available
        return true;
    }

    public static String getRealPathFromURI(Context context, Uri contentUri) {//通过本地路经 content://得到URI路径
        Cursor cursor = null;
        String locationPath = null;
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            locationPath = cursor.getString(column_index);
        } catch (Exception e) {
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return locationPath;
    }

    public static String getDiskCacheDir(Context context) {
        String cachePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            try {
                cachePath = context.getExternalCacheDir().getPath();
            } catch (Exception e) {
                cachePath = context.getCacheDir().getPath();
            }

        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return cachePath;
    }

    public static String getDiskFileDir(Context context) {
        String cachePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
//            Log.e("zwj","...............Environment.MEDIA_MOUNTED="+Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()));
//
//            Log.e("zwj","...............Environment.isExternalStorageRemovable()="+Environment.isExternalStorageRemovable());
            try {
                cachePath = context.getExternalFilesDir("data").getPath();
            } catch (Exception e) {
                cachePath = context.getFilesDir().getPath();
            }

        } else {
            cachePath = context.getFilesDir().getPath();
        }
        return cachePath;
    }

    /**
     * 获得当前时间
     *
     * @return
     */
    public static String getNowDate() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(date);
    }

    //版本名
    public static String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    //版本号
    public static String getVersionCode(Context context) {
        return String.valueOf(getPackageInfo(context).versionCode);
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    public static boolean isPhoneNum(String phone) {
        String regEx = "1[0-9]{10}";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(phone);
        boolean b = matcher.matches();
        return b;
    }

    public static String DateFormat(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    public static String DateFormatFull(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return format.format(date);
    }

    public static String DateFormatSysNotice(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    public static long Date2Millis(String dateString) {
        SimpleDateFormat mat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return mat.parse(dateString).getTime();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }

    public static boolean isContainChinese(String str) {

        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * 重新计算ListView的高度，解决ScrollView和ListView两个View都有滚动的效果，在嵌套使用时起冲突的问题
     *
     * @param listView
     */
    public static void setListViewHeight(ListView listView) {

        // 获取ListView对应的Adapter

        ListAdapter listAdapter = listView.getAdapter();

        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    public static byte[] sha1(String val) throws NoSuchAlgorithmException,
            UnsupportedEncodingException {
        byte[] data = val.getBytes("utf-8");
        MessageDigest mDigest = MessageDigest.getInstance("sha1");
        return mDigest.digest(data);
    }

    public static boolean isAppRunning(Context context) {
        // Returns a list of application processes that are running on the
        // device

        ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }

//    public static void back2Foreground(Context context) {
//        try {
//            ActivityManager mAm = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
//            //获得当前运行的task
//            List<ActivityManager.RunningTaskInfo> taskList = mAm.getRunningTasks(100);
//            for (ActivityManager.RunningTaskInfo rti : taskList) {
//                //找到当前应用的task，并启动task的栈顶activity，达到程序切换到前台
//                if (rti.topActivity.getPackageName().equals(context.getPackageName())) {
//                    mAm.moveTaskToFront(rti.id, 0);
//                    return;
//                }
//            }
//            //若没有找到运行的task，用户结束了task或被系统释放，则重新启动mainactivity
//            Intent resultIntent = new Intent(context, SplashScreenActivity.class);
//            resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
//            context.startActivity(resultIntent);
//        } catch (Exception e) {
//            Log.e("zwj", e.toString());
//        }
//    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    public static boolean isTaobao(String str) {
        Pattern pattern = Pattern.compile("^(http|https):\\/\\/(\\w*\\.|)(taobao|tmall)\\.com(.*?)");
        Matcher isTaobao = pattern.matcher(str);
        if (!isTaobao.matches()) {
            return false;
        }
        return true;
    }

    public static boolean isApkExist(String apkPath, long fileLen) {
        File file = new File(
                apkPath);
        if (file.exists()) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(
                        apkPath);
                int len = 0;
                int readedSize = 0;
                byte[] buffer = new byte[1024];
                while (-1 != (len = fis
                        .read(buffer))) {
                    readedSize += len;
                }
                if (fileLen != readedSize) {
                    return false;
                } else {

                    return true;
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        } else {
            return false;
        }
    }

    public static String showNum(int num) {
        if (num > 9999) {
            return num / 10000 + "万";
        }
        return num + "";
    }

    public static boolean hasSDCard() {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED)) {
            return false;
        }
        return true;
    }

    public static String getRootFilePath() {
        if (hasSDCard()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();// filePath:/sdcard/
        } else {
            return Environment.getDataDirectory().getAbsolutePath() + "/data"; // filePath:
        }
    }

    public static String saleNum(String sale) {
        String s = sale;
        if (!TextUtils.isEmpty(sale)) {
            int count = Integer.valueOf(sale);
            if (count > 9999) {
                int b = count / 10000;
                int yu = count % 10000 / 1000;
                s = b + "." + yu + "万";
            }
        }
        return s;
    }

    //判断控件是否显示在屏幕上
    public static boolean isShowScreen(Activity activity, View v) {
        Point p = new Point();
        activity.getWindowManager().getDefaultDisplay().getSize(p);
        int screenWidth = p.x;
        int screenHeight = p.y;
        Rect rect = new Rect(0, 0, screenWidth, screenHeight);
        int[] location = new int[2];
        v.getLocationInWindow(location);
        System.out.println(Arrays.toString(location));
        if (v.getLocalVisibleRect(rect)) {
            /*rect.contains(ivRect)*/
            return true;
        } else {
            return false;
        }
    }

    public static Bitmap returnBitMap(String url) {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static String formatDouble(String s){
        if (!s.contains(".")){
            return s+".00";
        }else {
            int index=s.lastIndexOf(".");
            if (s.substring(index+1,s.length()).length()==1){
                return s+"0";
            }else {
                return s;
            }
        }
    }

    //输入日期得出星期几
    //  String pTime = "2012-03-12";
    public static String getWeek(String pTime) {
        String Week = "星期";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        try {

            c.setTime(format.parse(pTime));

        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            Week += "日";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
            Week += "一";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY) {
            Week += "二";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) {
            Week += "三";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY) {
            Week += "四";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
            Week += "五";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
            Week += "六";
        }
        return Week;
    }

    public static String getFixLenthString() {
        String s="";
        int a[] = new int[10];
        for(int i=0;i<a.length;i++ ) {
            a[i] = (int)(10*(Math.random()));
            s+=a[i];
        }
        return s;
    }

    public static void setImgTransparent(Activity activity){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        }
    }
    /**
     * java转换数字以万为单位
     * @param num 要转化的数字
     * @param digit 保留的位数 可传null
     * @return
     */
    public static String numConvert(int num, Integer digit) {
        if(num < 10000){
            return num+"";
        }
        String unit = "万";
        double newNum = num / 10000.0;
        if(digit != null){
            String numStr = String.format("%." +digit +"f", newNum);
            return numStr + unit;
        }
        return newNum + unit;
    }
    /**
     * java转换数字以万为单位,自定义单位
     * @param num 要转化的数字
     * @param digit 保留的位数 可传null
     * @return
     */
    public static String numConvert(int num, Integer digit,String unit) {
        if(num < 10000){
            return num+"";
        }
        if (unit==null)
            unit="";
        double newNum = num / 10000.0;
        if(digit != null){
            String numStr = String.format("%." +digit +"f", newNum);
            return numStr + unit;
        }
        return newNum + unit;
    }
    /**
     * java转换数字以万为单位，并去掉多余的0
     * @param num 要转化的数字
     * @param digit 保留的位数 可传null
     * @return
     */
    public static String numConvertSubZero(int num, Integer digit) {
        if(num < 10000){
            return num+"";
        }
        String unit = "万";
        double newNum = num / 10000.0;
        if(digit != null){
            String numStr = String.format("%." +digit +"f", newNum);
            return subZeroAndDot(numStr) + unit;
        }
        return newNum + unit;
    }
    /**
     * java转换数字以万为单位，并去掉多余的0，自定义单位
     * @param num 要转化的数字
     * @param digit 保留的位数 可传null
     * @return
     */
    public static String numConvertSubZero(int num, Integer digit,String unit) {
        if(num < 10000){
            return num+"";
        }
        if (unit==null)
            unit="";
        double newNum = num / 10000.0;
        if(digit != null){
            String numStr = String.format("%." +digit +"f", newNum);
            return subZeroAndDot(numStr) + unit;
        }
        return newNum + unit;
    }
    /**
     * 使用java正则表达式去掉多余的.与0
     * @param s
     * @return
     */
    public static String subZeroAndDot(String s){
        if(s.indexOf(".") > 0){
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }

    public static String parseMoneySep( int bd) {
        DecimalFormat df = new DecimalFormat("#,###");
        return df.format(bd);
    }


}
